package m.member.order.action;

import m.common.action.ActionMeta;
import m.common.action.VuePageResult;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.*;
import m.member.manage.action.MemberInfoAction;
import m.member.manage.model.MemberLevel;
import m.member.order.model.MemberRecharge;
import m.member.order.service.MemberRechargeService;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import manage.action.ManageAction;
import manage.model.OrgGroupView;

import java.util.Date;

@ActionMeta(name = "member/order/memberRecharge")
public class MemberRechargeAction extends ManageAction {
    private MemberRecharge model;
    public JSONMessage doSave() throws Exception {
        verifyAdminOperPower("recharge_input_power");
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        model.setInputDate(new Date());
        String msg=getService(MemberRechargeService.class).save(model,getSessionAdmin(),org.getDept());
        return new JSONMessage(0)
                .push("msg",msg);
    }
    public JSONMessage doConfirm() throws Exception {
        verifyAdminOperPower("recharge_confirm_power");
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        getService(MemberRechargeService.class).confirm(model,getSessionAdmin(),org.getDept());
        return new JSONMessage(0)
                .push("msg","确认成功");
    }
    public VueResult toEdit() throws Exception {
        verifyAdminOperPower("recharge_input_power");
        if(ObjectUtil.isEmptyOid(model)){
            OrgGroupView org=getSessionOrgGroup();
            if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
                throw new MException(this.getClass(),"无店铺信息");
            model=new MemberRecharge();
            model.setType("A");
            model.setPayAmount(0d);
            model.setGiveAmount(0d);
            model.setGivePoint(0);
            model.setInputDate(new Date());
            model.setInputAdmin(getSessionAdmin());
            model.setServeAdmin(getSessionAdmin());
            model.setInputDept(org.getDept());
        }else{
            model= ModelQueryList.getModel(model,"*","member.*","member.level.*","serveAdmin.*","inputAdmin.*","inputDept.*");
            String pn=model.getMember().getPhoneNum();
            model.getMember().setPhoneNum(pn.substring(0,3)+"****"+pn.substring(pn.length()-4));
        }
        ModelForm form=new ModelForm("会员充值");
        form.addItem(
            FormInput.selectOneModel("会员信息","model","member","'"+actionUrl(MemberInfoAction.class,"selectList")+"'",750,
                    Element.tag("template").A("v-if","model.member.oid")
                    .E(Element.tag("a-tag").A(":color","model.member.level.color").E("{{model.member.level.name}}"))
                    .E("{{model.member.realName}} {{model.member.phoneNum}}").toString()
                ).setSpan(2),
            FormTest.test("confirmPower",FormInput.selectOneAdmin("服务员","model","serveAdmin","model.inputDept.oid","","{{model.serveAdmin.realname}}"))
                    .other(FormHtml.ins("服务员","{{model.serveAdmin.realname}}")),
            FormInput.radio("付款类型","model.type","m.member.order.model.MemberRecharge!type").setSpan(3),
            FormInput.number("付款金额","model.payAmount","元").setPlaceholder("请输入付款金额"),
            FormInput.number("赠送金额","model.giveAmount","元").setPlaceholder("请输入赠送金额"),
            FormInput.number("赠送积分","model.givePoint","分").setPlaceholder("请输入赠送积分"),
            FormInput.textarea("备注","model.remark").setPlaceholder("请输入备注").setSpan(3),
            FormHtml.ins("录入人","{{model.inputAdmin.realname}}"),
            FormHtml.ins("录入店铺","{{model.inputDept.name}}"),
            FormHtml.ins("录入时间","{{formatDate(model.inputDate,'yyyy-MM-dd')}}")
        )
        .addData("model",model).addData("confirmPower",hasAdminOperPower("recharge_confirm_power"))
        .addButton(
            FormButton.pri("保存","save")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("save",actionUrl("doSave"),"{model:this.model}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form);
//        以上写法可根据系统设置统一样式，下面写法是前端页面写法
//        return new VuePageResult("page/member/order/editMemberRecharge.js")
//                .addParam("model", model)
//                .addParam("confirmPower",hasAdminOperPower("recharge_confirm_power"));
    }
    public JSONMessage doSetType() throws Exception {
        verifyAdminOperPower("recharge_confirm_power");
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        getService(MemberRechargeService.class).setType(model,getSessionAdmin(),org.getDept());
        return new JSONMessage(0)
                .push("msg","操作成功");
    }
    public VueResult toSetType() throws Exception {
        model= ModelQueryList.getModel(model,"*","member.*","member.level.*","serveAdmin.*","inputAdmin.*","inputDept.*");
        String pn=model.getMember().getPhoneNum();
        model.getMember().setPhoneNum(pn.substring(0,3)+"****"+pn.substring(pn.length()-4));
        ModelForm form=new ModelForm("会员充值");
        form.addItem(
            FormHtml.ins("会员信息",
                Element.tag("a-tag").A(":color","model.member.level.color").E("{{model.member.level.name}}").toString()
                +"{{model.member.realName}} {{model.member.phoneNum}}").setSpan(2),
            FormHtml.ins("会员信息","{{model.serveAdmin.realname}}"),
            FormInput.radio("付款类型","model.type","m.member.order.model.MemberRecharge!type").setSpan(2),
            FormHtml.ins("付款金额","{{model.payAmount}}元"),
            FormInput.textarea("备注","model.remark").setPlaceholder("请输入备注").setSpan(3),
            FormHtml.ins("录入人","{{model.inputAdmin.realname}}"),
            FormHtml.ins("录入店铺","{{model.inputDept.name}}"),
            FormHtml.ins("录入时间","{{formatDate(model.inputDate,'yyyy-MM-dd')}}")
        )
        .addData("model",model)
        .addButton(
            FormButton.pri("确认补交赊账","setType").setConfirm("补交后请点击确认")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("setType",actionUrl("doSetType"),"{model:this.model}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form);
//        以上写法可根据系统设置统一样式，下面写法是前端页面写法
//        return new VuePageResult("page/member/order/setRechargeType.js")
//                .addParam("model", model);
    }
    /*
     * 会员充值记录
     */
    public VueResult allList() throws Exception {
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        String menu=getParamsValue("menu");
        VueListResult result=getVueListResult("会员充值记录", MemberRecharge.class,actionUrl("allList"));
        result.setFunction(true,false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addQueryFields("member.level.color","member.level.name");
        result.addCol(toTextColumn("会员级别", "member.level.oid", 100, true)
            .addElement(new ListElement("a-tag")
                .addAttr(":color","record.member.level.color")
                .addText("{{record.member.level.name}}")
            )
            .setDictType(MemberLevel.class)
            .setAlign(Align.CENTER)
        );
        result.addCol(toLinkColumn("会员", "member.realName", 100, true,
            new ListEvent(actionUrl(MemberInfoAction.class,"toView"),EventType.MODAL,1000)
                .addParam("model.oid","member.oid")
        ));
        result.addCol(toTextColumn("服务员", "serveAdmin.realname", 100, true));
        result.addCol(toTextColumn("付款类型","type",100,true).setDictType("m.member.order.model.MemberRecharge!type")
            .addElement(ListElement.test("text",
                new ListElement("a-tag")
                    .addAttr(":color","decode(text,'A','processing','B','success','C','error','D','warning','default')")
                    .addText("{{dict('m.member.order.model.MemberRecharge!type',text)}}")
            ))
            .addElement(ListElement.elseOther(
                new ListElement("a-tag")
                    .addAttr(":color","'#cf1322'")
                    .addText("赊账")
            ))
            .setAlign(Align.CENTER)
        );
        result.addCol(toNumberColumn("付款金额", "payAmount", 100, true));
        result.addCol(toNumberColumn("赠送金额", "giveAmount", 100, true));
        result.addCol(toIntegerColumn("赠送积分", "givePoint", 100, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(toDateColumn("录入时间", "inputDate", 100, true));
        result.addSearch(ListSearch.custom("菜单类型","menu", SearchType.HIDDEN_EQ));
        //菜单区分
        if(!"input".equals(menu)) {
            result.addCol(toTextColumn("录入人", "inputAdmin.realname", 100, true));
        }
        if("done".equals(menu)) {
            result.addCol(toTextColumn("店铺", "inputDept.name", 100, true));
            result.addCol(toTextColumn("确认人", "confirmAdmin.realname", 100, true));
            result.addCol(toDateColumn("确认时间", "confirmDate", 100, true));
        }
        if("input".equals(menu)&&hasAdminOperPower("recharge_input_power")){
            result.addCondition(QueryCondition.eq("inputAdmin.oid",getSessionAdminOid()));
            result.addCondition(QueryCondition.eq("inputDept.oid",org.getDept().getOid()));
            result.addCondition(QueryCondition.eq("status","N"));
            result.addCol(toSpaceColumn("操作", 100,
                ListButton.modal("修改", ButtonType.PRIMARY, actionUrl("toEdit"), 900, SuccessMethod.REFRESH)
                    .addParam("model.oid", "oid")
            ).setFixed(Align.RIGHT));
            result.addButton(ListButton.modal("新增", ButtonType.PRIMARY, actionUrl("toEdit"), 900, SuccessMethod.REFRESH));
        }else if("confirm".equals(menu)&&hasAdminOperPower("recharge_confirm_power")){
            result.setSubTitle("请及时确认充值");
            result.addCondition(QueryCondition.eq("inputDept.oid",org.getDept().getOid()));
            result.addCondition(QueryCondition.eq("status","N"));
            result.addCol(toSpaceColumn("操作", 100,
                ListButton.ajax("确认", ButtonType.PRIMARY, actionUrl("doConfirm"), SuccessMethod.REFRESH)
                    .addParam("model.oid", "oid").setConfirm("确认后生效且不可修改，该记录已核实了吗？")
            ).setFixed(Align.RIGHT));
        }else if("done".equals(menu)){
            if(!hasAdminOperPower("recharge_confirm_power")) {
                result.setSubTitle("我负责的已完成充值");
                result.addCondition(QueryCondition.eq("inputAdmin.oid", getSessionAdminOid()));
            }else{
                result.setSubTitle("店铺的已完成充值");
            }
            result.addCondition(QueryCondition.notEmpty("type"));
            result.addCondition(QueryCondition.eq("inputDept.oid",org.getDept().getOid()));
            result.addCondition(QueryCondition.eq("status","Y"));
        }else if("creditConfirm".equals(menu)){
            result.setSubTitle("赊账补齐后请在此确认");
            result.addCondition(QueryCondition.isEmpty("type"));
            result.addCondition(QueryCondition.eq("inputDept.oid",org.getDept().getOid()));
            result.addCondition(QueryCondition.eq("status","Y"));
            result.addCol(toSpaceColumn("操作", 100,
                ListButton.modal("补交", ButtonType.PRIMARY, actionUrl("toSetType"),900, SuccessMethod.REFRESH)
                    .addParam("model.oid", "oid")
            ).setFixed(Align.RIGHT));
        }
        //排序 result.addOrder
        //查询条件 result.addCondition
        return result;
    }
    /*
     * 会员充值记录
     */
    public VueResult memberRechargeList() throws Exception {
        VueListResult result=getVueListResult("充值记录", MemberRecharge.class,actionUrl("memberRechargeList"));
        result.setFunction(true,false);
        result.hideHead();
        result.setPageSize(10);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("店铺", "inputDept.name", 100, true));
        result.addCol(toTextColumn("服务员", "serveAdmin.realname", 100, true));
        result.addCol(toDateColumn("录入时间", "inputDate", 100, true));
        result.addCol(toTextColumn("状态","status",80,true).setDictType("m.member.order.model.MemberRecharge!status").setAlign(Align.CENTER));
        result.addCol(toTextColumn("付款类型","type",100,true).setDictType("m.member.order.model.MemberRecharge!type")
            .addElement(ListElement.test("text",
                new ListElement("a-tag")
                    .addAttr(":color","decode(text,'A','processing','B','success','C','error','D','warning','default')")
                    .addText("{{dict('m.member.order.model.MemberRecharge!type',text)}}")
            ))
            .addElement(ListElement.elseOther(
                new ListElement("a-tag")
                    .addAttr(":color","'#cf1322'")
                    .addText("赊账")
            ))
            .setAlign(Align.CENTER)
        );
        result.addCol(toNumberColumn("付款金额", "payAmount", 100, true));
        result.addCol(toNumberColumn("赠送金额", "giveAmount", 100, true));
        result.addCol(toIntegerColumn("赠送积分", "givePoint", 100, true));
        result.addCol(toTextColumn("备注", "remark", 100, true));
        result.addCol(toTextColumn("录入人", "inputAdmin.realname", 100, true));
        result.addSearch(ListSearch.field("会员oid","member.oid",SearchType.HIDDEN_EQ));
        return result;
    }

    public MemberRecharge getModel() {
        return model;
    }

    public void setModel(MemberRecharge model) {
        this.model = model;
    }
}
